home *** CD-ROM | disk | FTP | other *** search
/ MPEG Toolkit / MPEG Toolkit.iso / dos / ampeg43 / source / encodsrc / musicout.c < prev    next >
Encoding:
C/C++ Source or Header  |  1997-01-01  |  18.4 KB  |  463 lines

  1. /**********************************************************************
  2. Copyright (c) 1991 MPEG/audio software simulation group, All Rights Reserved
  3. musicout.c
  4. **********************************************************************/
  5. /**********************************************************************
  6.  * MPEG/audio coding/decoding software, work in progress              *
  7.  *   NOT for public distribution until verified and approved by the   *
  8.  *   MPEG/audio committee.  For further information, please contact   *
  9.  *   Davis Pan, 508-493-2241, e-mail: pan@3d.enet.dec.com             *
  10.  *                                                                    *
  11.  * VERSION 3.9                                                        *
  12.  *   changes made since last update:                                  *
  13.  *   date   programmers                comment                        *
  14.  * 2/25/91  Douglas Wong        start of version 1.0 records          *
  15.  * 3/06/91  Douglas Wong        rename setup.h to dedef.h             *
  16.  *                              removed extraneous variables          *
  17.  *                              removed window_samples (now part of   *
  18.  *                              filter_samples)                       *
  19.  * 3/07/91  Davis Pan           changed output file to "codmusic"     *
  20.  * 5/10/91  Vish (PRISM)        Ported to Macintosh and Unix.         *
  21.  *                              Incorporated new "out_fifo()" which   *
  22.  *                              writes out last incomplete buffer.    *
  23.  *                              Incorporated all AIFF routines which  *
  24.  *                              are also compatible with SUN.         *
  25.  *                              Incorporated user interface for       *
  26.  *                              specifying sound file names.          *
  27.  *                              Also incorporated user interface for  *
  28.  *                              writing AIFF compatible sound files.  *
  29.  * 27jun91  dpwe (Aware)        Added musicout and &sample_frames as  *
  30.  *                              args to out_fifo (were glob refs).    *
  31.  *                              Used new 'frame_params' struct.       *
  32.  *                              Clean,simplify, track clipped output  *
  33.  *                              and total bits/frame received.        *
  34.  * 7/10/91  Earle Jennings      changed to floats to FLOAT            *
  35.  *10/ 1/91  S.I. Sudharsanan,   Ported to IBM AIX platform.           *
  36.  *          Don H. Lee,                                               *
  37.  *          Peter W. Farrett                                          *
  38.  *10/ 3/91  Don H. Lee          implemented CRC-16 error protection   *
  39.  *                              newly introduced functions are        *
  40.  *                              buffer_CRC and recover_CRC_error      *
  41.  *                              Additions and revisions are marked    *
  42.  *                              with "dhl" for clarity                *
  43.  * 2/11/92  W. Joseph Carter    Ported new code to Macintosh.  Most   *
  44.  *                              important fixes involved changing     *
  45.  *                              16-bit ints to long or unsigned in    *
  46.  *                              bit alloc routines for quant of 65535 *
  47.  *                              and passing proper function args.     *
  48.  *                              Removed "Other Joint Stereo" option   *
  49.  *                              and made bitrate be total channel     *
  50.  *                              bitrate, irrespective of the mode.    *
  51.  *                              Fixed many small bugs & reorganized.  *
  52.  *19 aug 92 Soren H. Nielsen    Changed MS-DOS file name extensions.  *
  53.  * 8/27/93 Seymour Shlien,      Fixes in Unix and MSDOS ports,        *
  54.  *         Daniel Lauzon, and                                         *
  55.  *         Bill Truerniet                                             *
  56.  **********************************************************************/
  57.  
  58. #include        "common.h"
  59. #include        "decoder.h"
  60.  
  61. /********************************************************************
  62. /*
  63. /*        This part contains the MPEG I decoder for Layers I & II.
  64. /*
  65. /*********************************************************************/
  66.  
  67. /****************************************************************
  68. /*
  69. /*        For MS-DOS user (Turbo c) change all instance of malloc
  70. /*        to _farmalloc and free to _farfree. Compiler model hugh
  71. /*        Also make sure all the pointer specified are changed to far.
  72. /*
  73. /*****************************************************************/
  74.  
  75. /*********************************************************************
  76. /*
  77. /* Core of the Layer II decoder.  Default layer is Layer II.
  78. /*
  79. /*********************************************************************/
  80.  
  81. /* Global variable definitions for "musicout.c" */
  82.  
  83. char *programName;
  84.  
  85. /* Implementations */
  86.  
  87. main(argc, argv)
  88. int argc;
  89. char **argv;
  90. {
  91. typedef short PCM[2][3][SBLIMIT];
  92.     PCM FAR *pcm_sample;
  93. typedef unsigned int SAM[2][3][SBLIMIT];
  94.     SAM FAR *sample;
  95. typedef double FRA[2][3][SBLIMIT];
  96.     FRA FAR *fraction;
  97. typedef double VE[2][HAN_SIZE];
  98.     VE FAR *w;
  99.  
  100.     Bit_stream_struc  bs;
  101.     frame_params      fr_ps;
  102.     layer             info;
  103.     FILE              *musicout;
  104.     unsigned long     sample_frames;
  105.  
  106.     int               i, j, k, stereo, done=FALSE, clip, sync;
  107.     int               error_protection, crc_error_count, total_error_count;
  108.     int               x;
  109.     char              default_file_name[MAX_NAME_SIZE]; 
  110.     unsigned int      old_crc, new_crc;
  111.     unsigned int      bit_alloc[2][SBLIMIT], scfsi[2][SBLIMIT],
  112.                       scale_index[2][3][SBLIMIT];
  113.     unsigned long     bitsPerSlot, samplesPerFrame, frameNum = 0;
  114.     unsigned long     frameBits, gotBits = 0;
  115.     IFF_AIFF          pcm_aiff_data;
  116.     char              encoded_file_name[MAX_NAME_SIZE];
  117.     char              decoded_file_name[MAX_NAME_SIZE];
  118.     char              t[50];
  119.     int               need_aiff;
  120.     int topSb = 0;
  121.  
  122. #ifdef  MACINTOSH
  123.     console_options.nrows = MAC_WINDOW_SIZE;
  124.     argc = ccommand(&argv);
  125. #endif
  126.  
  127.     /* Most large variables are declared dynamically to ensure
  128.        compatibility with smaller machines */
  129.  
  130.     pcm_sample = (PCM FAR *) mem_alloc((long) sizeof(PCM), "PCM Samp");
  131.     sample = (SAM FAR *) mem_alloc((long) sizeof(SAM), "Sample");
  132.     fraction = (FRA FAR *) mem_alloc((long) sizeof(FRA), "fraction");
  133.     w = (VE FAR *) mem_alloc((long) sizeof(VE), "w");
  134.  
  135.     fr_ps.header = &info;
  136.     fr_ps.tab_num = -1;                /* no table loaded */
  137.     fr_ps.alloc = NULL;
  138.     for (i=0;i<HAN_SIZE;i++) for (j=0;j<2;j++) (*w)[j][i] = 0.0;
  139.  
  140.     programName = argv[0];
  141.     if(argc==1) {        /* no command line args -> interact */
  142.        do {
  143.           printf ("Enter encoded file name <required>: ");
  144.           gets (encoded_file_name);
  145.           if (encoded_file_name[0] == NULL_CHAR)
  146.              printf ("Encoded file name is required. \n");
  147.        } while (encoded_file_name[0] == NULL_CHAR);
  148.        printf (">>> Encoded file name is: %s \n", encoded_file_name);
  149.        
  150.     x=0;
  151.     while (x <= MAX_NAME_SIZE)
  152.     {
  153.         default_file_name[x] = NULL_CHAR;
  154.         ++x;
  155.         }
  156.     x=0;
  157.     while (x <= 8)
  158.     {
  159.    default_file_name[x] = encoded_file_name[x];
  160.     if (encoded_file_name[++x] == '.') 
  161.         x = 9;
  162.   
  163.     }
  164.     
  165.  
  166.     strcat(default_file_name,DFLT_OPEXT);
  167.  
  168.     printf("Enter MPEG decoded output file name <%s>: ",
  169.            default_file_name); /* 92-08-19 shn */
  170.     gets(decoded_file_name);
  171.     if (decoded_file_name[0] == NULL_CHAR) {
  172.  
  173.         /* replace old extension with new one, 92-08-19 shn */
  174.        strcpy(decoded_file_name,default_file_name);
  175.     }
  176.        
  177.       
  178.    
  179.        printf (">>> MPEG decoded file name is: %s \n", decoded_file_name);
  180.  
  181.        printf(
  182.           "Do you wish to write an AIFF compatible sound file ? (y/<n>) : ");
  183.        gets(t);
  184.        if (*t == 'y' || *t == 'Y') need_aiff = TRUE;
  185.        else                        need_aiff = FALSE;
  186.        if (need_aiff)
  187.             printf(">>> An AIFF compatible sound file will be written\n");
  188.        else printf(">>> A non-headered PCM sound file will be written\n");
  189.  
  190.        printf(
  191.           "Do you wish to exit (last chance before decoding) ? (y/<n>) : ");
  192.        gets(t);
  193.        if (*t == 'y' || *t == 'Y') exit(0);
  194.     }
  195.     else {        /* interpret CL Args */
  196.        int i=0, err=0;
  197.  
  198.        need_aiff = FALSE;
  199.        encoded_file_name[0] = '\0';
  200.        decoded_file_name[0] = '\0';
  201.  
  202.        while(++i<argc && err == 0) {
  203.           char c, *token, *arg, *nextArg;
  204.           int  argUsed;
  205.  
  206.           token = argv[i];
  207.           if(*token++ == '-') {
  208.              if(i+1 < argc) nextArg = argv[i+1];
  209.              else           nextArg = "";
  210.              argUsed = 0;
  211.              while(c = *token++) {
  212.                 if(*token /* NumericQ(token) */) arg = token;
  213.                 else                             arg = nextArg;
  214.                 switch(c) {
  215.                    case 's':  topSb = atoi(arg); argUsed = 1;
  216.                       if(topSb<1 || topSb>SBLIMIT) {
  217.                          fprintf(stderr, "%s: -s band %s not %d..%d\n",
  218.                                  programName, arg, 1, SBLIMIT);
  219.                          err = 1;
  220.                       }
  221.                       break;
  222.                    case 'A':  need_aiff = TRUE; break;
  223.                    default:   fprintf(stderr,"%s: unrecognized option %c\n",
  224.                                       programName, c);
  225.                       err = 1; break;
  226.                 }
  227.                 if(argUsed) {
  228.                    if(arg == token) token = ""; /* no more from token */
  229.                    else             ++i; /* skip arg we used */
  230.                    arg = ""; argUsed = 0;
  231.                 }
  232.              }
  233.           }
  234.           else {
  235.              if(encoded_file_name[0] == '\0')
  236.                 strcpy(encoded_file_name, argv[i]);
  237.              else
  238.                 if(decoded_file_name[0] == '\0')
  239.                    strcpy(decoded_file_name, argv[i]);
  240.                 else {
  241.                    fprintf(stderr,
  242.                            "%s: excess arg %s\n", programName, argv[i]);
  243.                    err = 1;
  244.                 }
  245.           }
  246.        }
  247.  
  248.        if(err || encoded_file_name[0] == '\0') usage();  /* never returns */
  249.  
  250.        if(decoded_file_name[0] == '\0') {
  251.           strcpy(decoded_file_name, encoded_file_name);
  252.           strcat(decoded_file_name, DFLT_OPEXT);
  253.        }
  254.  
  255.     }
  256.     /* report results of dialog / command line */
  257.     printf("Input file = '%s'  output file = '%s'\n",
  258.            encoded_file_name, decoded_file_name);
  259.     if(need_aiff) printf("Output file written in AIFF format\n");
  260.  
  261.     if(strcmp(decoded_file_name,"stdout") == 0) musicout = stdout;
  262.     else {
  263.          if ((musicout = fopen(decoded_file_name, "w+b")) == NULL) {
  264.             printf ("Could not create \"%s\".\n", decoded_file_name);
  265.             exit(1);
  266.          }
  267.     }
  268.  
  269.     open_bit_stream_r(&bs, encoded_file_name, BUFFER_SIZE);
  270.  
  271.     if (need_aiff)
  272.        if (aiff_seek_to_sound_data(musicout) == -1) {
  273.           printf("Could not seek to PCM sound data in \"%s\".\n",
  274.                  decoded_file_name);
  275.           exit(1);
  276.        }
  277.  
  278.     sample_frames = 0;
  279.  
  280.     while (!end_bs(&bs)) {
  281.  
  282.        sync = seek_sync(&bs, SYNC_WORD, SYNC_WORD_LNGTH);
  283.        frameBits = sstell(&bs) - gotBits;
  284.        if(frameNum > 0)        /* don't want to print on 1st loop; no lay */
  285.           if(frameBits%bitsPerSlot)
  286.              fprintf(stderr,"Got %ld bits = %ld slots plus %ld\n",
  287.                      frameBits, frameBits/bitsPerSlot, frameBits%bitsPerSlot);
  288.        gotBits += frameBits;
  289.  
  290.        if (!sync) {
  291.           printf("Frame cannot be located\n");
  292.           printf("Input stream may be empty\n");
  293.           done = TRUE;
  294.           /* finally write out the buffer */
  295.           if (info.lay == 2) out_fifo(*pcm_sample, 3, &fr_ps, done,
  296.                                       musicout, &sample_frames);
  297.           else               out_fifo(*pcm_sample, 1, &fr_ps, done,
  298.                                       musicout, &sample_frames);
  299.           break;
  300.        }
  301.  
  302.        decode_info(&bs, &fr_ps);
  303.        hdr_to_frps(&fr_ps);
  304.        stereo = fr_ps.stereo;
  305.        error_protection = info.error_protection;
  306.        crc_error_count = 0;
  307.        total_error_count = 0;
  308.        if(frameNum == 0) WriteHdr(&fr_ps, stdout);  /* printout layer/mode */
  309.  
  310.        fprintf(stderr, "{%4lu}\r", frameNum++); fflush(stderr);
  311.        if (error_protection) buffer_CRC(&bs, &old_crc);
  312.  
  313.        switch (info.lay) {
  314.  
  315.           case 1: {
  316.              bitsPerSlot = 32;        samplesPerFrame = 384;
  317.              I_decode_bitalloc(&bs,bit_alloc,&fr_ps);
  318.              I_decode_scale(&bs, bit_alloc, scale_index, &fr_ps);
  319.  
  320.              if (error_protection) {
  321.                 I_CRC_calc(&fr_ps, bit_alloc, &new_crc);
  322.                 if (new_crc != old_crc) {
  323.                    crc_error_count++;
  324.                    total_error_count++;
  325.                    recover_CRC_error(*pcm_sample, crc_error_count,
  326.                                      &fr_ps, musicout, &sample_frames);
  327.                    break;
  328.                 }
  329.                 else crc_error_count = 0;
  330.              }
  331.  
  332.              clip = 0;
  333.              for (i=0;i<SCALE_BLOCK;i++) {
  334.                 I_buffer_sample(&bs,(*sample),bit_alloc,&fr_ps);
  335.                 I_dequantize_sample(*sample,*fraction,bit_alloc,&fr_ps);
  336.                 I_denormalize_sample((*fraction),scale_index,&fr_ps);
  337.                 if(topSb>0)        /* clear channels to 0 */
  338.                    for(j=topSb; j<fr_ps.sblimit; ++j)
  339.                       for(k=0; k<stereo; ++k)
  340.                          (*fraction)[k][0][j] = 0;
  341.  
  342.                 for (j=0;j<stereo;j++) {
  343.                    clip += SubBandSynthesis (&((*fraction)[j][0][0]), j,
  344.                                              &((*pcm_sample)[j][0][0]));
  345.                 }
  346.                 out_fifo(*pcm_sample, 1, &fr_ps, done,
  347.                          musicout, &sample_frames);
  348.              }
  349.              if(clip > 0) printf("%d output samples clipped\n", clip);
  350.              break;
  351.           }
  352.  
  353.           case 2: {
  354.              bitsPerSlot = 8;        samplesPerFrame = 1152;
  355.              II_decode_bitalloc(&bs, bit_alloc, &fr_ps);
  356.              II_decode_scale(&bs, scfsi, bit_alloc, scale_index, &fr_ps);
  357.  
  358.              if (error_protection) { 
  359.                 II_CRC_calc(&fr_ps, bit_alloc, scfsi, &new_crc);
  360.                 if (new_crc != old_crc) {
  361.                    crc_error_count++;
  362.                    total_error_count++;
  363.                    recover_CRC_error(*pcm_sample, crc_error_count,
  364.                                      &fr_ps, musicout, &sample_frames);
  365.                    break;
  366.                 }
  367.                 else crc_error_count = 0;
  368.              }
  369.  
  370.              clip = 0;
  371.              for (i=0;i<SCALE_BLOCK;i++) {
  372.                 II_buffer_sample(&bs,(*sample),bit_alloc,&fr_ps);
  373.                 II_dequantize_sample((*sample),bit_alloc,(*fraction),&fr_ps);
  374.                 II_denormalize_sample((*fraction),scale_index,&fr_ps,i>>2);
  375.  
  376.                 if(topSb>0)        /* debug : clear channels to 0 */
  377.                    for(j=topSb; j<fr_ps.sblimit; ++j)
  378.                       for(k=0; k<stereo; ++k)
  379.                          (*fraction)[k][0][j] =
  380.                          (*fraction)[k][1][j] =
  381.                          (*fraction)[k][2][j] = 0;
  382.  
  383.                 for (j=0;j<3;j++) for (k=0;k<stereo;k++) {
  384.                    clip += SubBandSynthesis (&((*fraction)[k][j][0]), k,
  385.                                              &((*pcm_sample)[k][j][0]));
  386.                 }
  387.                 out_fifo(*pcm_sample, 3, &fr_ps, done, musicout,
  388.                          &sample_frames);
  389.              }
  390.              if(clip > 0) printf("%d samples clipped\n", clip);
  391.              break;
  392.           }
  393.  
  394.        }
  395.  
  396.     }
  397.  
  398.     if (need_aiff) {
  399.        pcm_aiff_data.numChannels       = stereo;
  400.        pcm_aiff_data.numSampleFrames   = sample_frames;
  401.        pcm_aiff_data.sampleSize        = 16;
  402.        pcm_aiff_data.sampleRate        = s_freq[info.sampling_frequency]*1000;
  403. #ifdef IFF_LONG       
  404.        pcm_aiff_data.sampleType        = IFF_ID_SSND;
  405. #else
  406.        strncpy(&pcm_aiff_data.sampleType,IFF_ID_SSND,4);
  407. #endif
  408.        pcm_aiff_data.blkAlgn.offset    = 0;
  409.        pcm_aiff_data.blkAlgn.blockSize = 0;
  410.  
  411.        if (aiff_write_headers(musicout, &pcm_aiff_data) == -1) {
  412.           printf("Could not write AIFF headers to \"%s\"\n",
  413.                  decoded_file_name);
  414.           exit(2);
  415.        }
  416.     }
  417.  
  418.     printf("Avg slots/frame = %.3f; b/smp = %.2f; br = %.3f kbps\n",
  419.            (FLOAT) gotBits / (frameNum * bitsPerSlot),
  420.            (FLOAT) gotBits / (frameNum * samplesPerFrame),
  421.            (FLOAT) gotBits / (frameNum * samplesPerFrame) *
  422.            s_freq[info.sampling_frequency]);
  423.  
  424.     close_bit_stream_r(&bs);
  425.     fclose(musicout);
  426.  
  427.     /* for the correct AIFF header information */
  428.     /*             on the Macintosh            */
  429.     /* the file type and the file creator for  */
  430.     /* Macintosh compatible Digidesign is set  */
  431.  
  432. #ifdef  MACINTOSH
  433.     if (need_aiff) set_mac_file_attr(decoded_file_name, VOL_REF_NUM,
  434.                                      CREATR_DEC_AIFF, FILTYP_DEC_AIFF);
  435.     else           set_mac_file_attr(decoded_file_name, VOL_REF_NUM,
  436.                                      CREATR_DEC_BNRY, FILTYP_DEC_BNRY);
  437. #endif
  438.  
  439.     printf("Decoding of \"%s\" is finished\n", encoded_file_name);
  440.     printf("The decoded PCM output file name is \"%s\"\n", decoded_file_name);
  441.     if (need_aiff)
  442.        printf("\"%s\" has been written with AIFF header information\n",
  443.               decoded_file_name);
  444.  
  445.     exit( 0 );
  446. }
  447.  
  448. static void usage()  /* print syntax & exit */
  449. {
  450.    fprintf(stderr,
  451.       "usage: %s                         queries for all arguments, or\n",
  452.        programName);
  453.    fprintf(stderr,
  454.       "       %s [-A][-s sb] inputBS [outPCM]\n", programName);
  455.    fprintf(stderr,"where\n");
  456.    fprintf(stderr," -A       write an AIFF output PCM sound file\n");
  457.    fprintf(stderr," -s sb    resynth only up to this sb (debugging only)\n");
  458.    fprintf(stderr," inputBS  input bit stream of encoded audio\n");
  459.    fprintf(stderr," outPCM   output PCM sound file (dflt inName+%s)\n",
  460.            DFLT_OPEXT);
  461.    exit(1);
  462. }
  463.